import { NextResponse, after, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { isAdmin } from '@/app/lib/admin'; import { stripe } from '@/app/lib/stripe'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { cancellationByStudioHtml, cancellationStudioInternalHtml } from '@/app/lib/order-emails'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // Admin-initiated cancel. Broader than the customer-side cancel // (which only works at `pending_design`) — admin can cancel from // any non-terminal status. Stripe refund auto-fires when there's a // payment_intent on file. Prodigi orders are NOT auto-cancelled — // if `prodigi_order_id` is set, admin must cancel via Prodigi // dashboard / API separately (handled out of band for now). // // 'abandoned' is also terminal here — there's no charge to refund // and nothing to cancel; just leave the row alone. const TERMINAL_STATUSES = new Set(['cancelled', 'abandoned']); export async function POST( req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { const { id } = await ctx.params; const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return NextResponse.json({ error: 'forbidden' }, { status: 403 }); } let body: { reason?: string }; try { body = await req.json(); } catch { body = {}; } const reason = (body.reason ?? '').trim() || null; const admin = commerceDb(); const { data: order, error: fetchErr } = await admin .from('orders') .select('id, user_email, status, price_cents, stripe_payment_intent_id, prodigi_order_id') .eq('id', id) .single(); if (fetchErr || !order) { return NextResponse.json({ error: 'Order not found.' }, { status: 404 }); } if (TERMINAL_STATUSES.has(order.status)) { return NextResponse.json({ error: `Order is already in terminal state "${order.status}". Nothing to cancel.`, }, { status: 409 }); } // Issue Stripe refund if there's a payment intent. Skip if no // charge exists yet (status: pending_payment). let refundId: string | null = null; let refundError: string | null = null; if (order.stripe_payment_intent_id) { try { const refund = await stripe().refunds.create({ payment_intent: order.stripe_payment_intent_id, reason: 'requested_by_customer', metadata: { orderId: order.id, source: 'admin-cancel', cancelReason: reason ?? '' }, }); refundId = refund.id; } catch (e) { console.error('[admin cancel] Stripe refund failed', e); refundError = e instanceof Error ? e.message : 'refund failed'; // Don't fail the whole cancel on a refund error — admin can // refund manually from the Stripe dashboard. Surface in // response so admin knows. } } // Warn if a Prodigi order exists — admin needs to cancel that // separately via Prodigi's UI/API. We mark our order cancelled // regardless so internal status reflects intent. const prodigiWarning = order.prodigi_order_id ? `This order already has a Prodigi reference (${order.prodigi_order_id}). Cancel the Prodigi order separately via dashboard/API — this endpoint does not auto-cancel print orders.` : null; await admin.from('orders').update({ status: 'cancelled', }).eq('id', id); // Notify the customer (separate template from customer-initiated // cancel — phrased as "we've cancelled" with an optional reason). // Sent in after() so a slow/stalled email send can't hold the HTTP response // open — the refund + status flip above are the parts the admin waits on; // email delivery is a side effect that runs after we've responded. after(async () => { await Promise.allSettled([ sendEmail({ to: order.user_email, subject: `Cancelled by Lumen & Gesso — ${displayOrderId(order.id)}`, html: cancellationByStudioHtml(order.id, order.price_cents, reason), text: `Your commission ${displayOrderId(order.id)} has been cancelled by our studio.${reason ? ` Reason: ${reason}.` : ''} A full refund of $${(order.price_cents / 100).toFixed(2)} has been issued${refundError ? ' (or will be — refund processing failed, the studio will follow up manually)' : ''} and typically lands within 5–10 business days.`, }), // Internal record so the studio inbox has a copy. sendEmail({ to: env.site.studioEmail(), subject: `[ADMIN CANCEL] ${displayOrderId(order.id)} — ${order.user_email}`, html: cancellationStudioInternalHtml(order.id, order.user_email, order.price_cents, { reason, refundId, refundError, prodigiOrderId: order.prodigi_order_id, }), text: `Admin cancelled order ${order.id} (${order.user_email}). Refund: ${refundId ?? (refundError ? 'FAILED — ' + refundError : 'no charge to refund')}. Prodigi: ${order.prodigi_order_id ?? 'none'}. Reason: ${reason ?? '(none)'}`, }), ]); }); return NextResponse.json({ ok: true, refundId, refundError, prodigiWarning, }); }